/**
 * Created by liujie on 2017/10/11.
 * 监控管理
 */
var express = require('express');
var request = require('request');
var Mock = require('mockjs');
var url = require('url');
var qstr = require("querystring");
var fs = require("fs");
var pro = require('../../property/cuspro');
var auth = require('../../auth/auth');
var util = require('../../util/commonutil');
var router = express.Router();
var resultJSON = require('../common/resultJSON');
var cache = require('memory-cache');
var _initCheckCarId = null;
var searchCarNo = false;

var cars = [
    {
        "id":1001,
        "address":"青岛市崂山区石老人海水浴场",
        "status":"1",
    },
    {
        "id":1002,
        "address":"青岛市崂山区科苑纬三路19号",
        "status":"0",
    },
    {
        "id":1003,
        "address":"青岛国际会展中心",
        "status":"0",
    },
    {
        "id":1004,
        "address":"青岛市市南区泰安路2号",
        "status":"3",
    },
    {
        "id":1005,
        "address":"山东省青岛市李沧区静乐路1号",
        "status":"2",
    },
    {
        "id":1006,
        "address":"山东省青岛市即墨滨海公路72号",
        "status":"2",
    }
];

var carTree = [
];
var carTreeJson = {};
var _carTreeObj = {};
var _carCountObj={};
function getTrees(treeDatas) {
    carTree = [];
    try{
        if(treeDatas && treeDatas.length){
            var treeItems = [];
            var rootTree;
            var _root =  {
                "baseProtocolType": 1,
                "code": "001",
                "deptManager": null,
                "id": 1,
                "isDeleted": false,
                "memo": null,
                "name": "GPS管理中心",
                "parentId": -1,
                "parentName": "所有客户",
                "phone": null,
                "pnum": 1,
                "uname": "GPS管理中心(0/1)",
                "work": null,
                "zx": 0
            };
            // console.log("输出>>"+treeDatas.length);
            for(var m=0;m<treeDatas.length;m++){
                // if(treeDatas[0].parentId == -1){
                //     _root = treeDatas[0];
                //     break;
                // }
                // else if(treeDatas[m].parentId == -1){
                //     console.log("输出>>"+treeDatas.length);
                //     _root = treeDatas[m]
                // }
                if(treeDatas[m].parentId == -1){
                    // console.log("输出>>"+treeDatas[m].parentId);
                    _root = treeDatas[m]
                }
            }
            rootTree = getTreeData(treeDatas,_root);
            rootTree["text"] = "<span class='carname'>"+_root["uname"]+"</span>";
            rootTree["state"]= {
                expanded:true,
                isHideCheck:true
            };
            //rootTree["state"]["isHideCheck"]= true
            //carTree[0]["nodes"].push(rootTree);
            carTree.push(rootTree)
        }
    }catch (err){
        console.log("查询车辆树结果失败"+err)
    }
}

function getTreeData(treeDatas,treeitem) {
    try{
        if(treeDatas && treeDatas.length){
            treeitem["nodes"] = [];
            for(var i=0;i<treeDatas.length;i++){
                var _treeData = treeDatas[i];
                _treeData["text"] = "<span class='carname'>"+_treeData["uname"]+"</span>";
                if(searchCarNo){
                    _treeData["state"]= {
                        expanded:true
                    };
                }else{
                    _treeData["state"]= {
                        expanded:false
                    };
                }
                if(_treeData["isCar"] == true){
                    if(_initCheckCarId && _treeData["id"] == _initCheckCarId){
                        _treeData["state"]["checked"]=true;
                        _treeData["state"]["selected"]=true;
                    }
                    // _treeData["color"] = "#0ae";
                    //warningType 1--在线 0-离线 2-在线停止 3-报警 5-超速
                    if(_treeData["warningType"] == 0){
                        _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-black.png'></span><span class='carname'>"+_treeData["text"]+"</span>";
                    }else if(_treeData["warningType"] == 1 || _treeData["warningType"] == 2){
                        _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-blue.png'></span><span class='carname'>"+_treeData["text"]+"</span>";
                    }
                    else if(_treeData["warningType"] == 3 || _treeData["warningType"] == 5 || _treeData["warningType"] == 8){
                        _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-red.png'></span><span class='carname'>"+_treeData["text"]+"</span>";
                    } else{
                        _treeData["text"] = "<span class='icon isCar'></span><span class='carname'>"+_treeData["text"]+"</span>";
                    }
                    if(!carTreeJson[_treeData["baseTerminalId"]]){
                        carTreeJson[_treeData["baseTerminalId"]] = _treeData;
                    }
                }else{
                    _treeData["state"]["isHideCheck"]= true;
                    if(_treeData["uname"].indexOf("无线设备(") == -1 && _treeData["uname"].indexOf("有线设备(") == -1){
                        _treeData["state"]["expanded"]= true;
                    }
                }
                if(_treeData["parentId"] == treeitem["id"]){
                    treeitem["nodes"].push(getTreeData(treeDatas,_treeData));
                }
            }
            return treeitem
        }
    }catch (err){
        console.log("查询车辆树结果失败"+err)
    }
};

router.get('/',function (req, res, next) {
    res.render("map/newMonitor",{"pointCarId":req.param("carId"),"baseCarNo":req.param("baseCarNo"),parentMenuList:false,sysMap:false});
});
router.post('/querySessionData',function (req, res, next) {
    carTree = [
    ];
    carTreeJson={};
    // console.log(req.session.treeData);
    //console.log(req.session.treeData.treeJson);
    try {
        var sid=auth.getSessionID(req, res, next);
        // console.log("------加载车辆数据-------");
        console.log(pro.loginUserId);

        pro.gClient.get("carTreeObj_"+pro.loginUserId,function (error, resu) {
            if(error) {
                console.log(error);
            } else {
                console.log(resu);
                console.log(pro.loginUserId);
                res.json(JSON.parse(resu));
            }
        });
    }catch (e){
        // res.redirect(307,"/monitor/queryTreeData");
    }

});

router.post('/queryDeptIdsRef',function (req, res, next) {
    try {
        var sid=auth.getSessionID(req, res, next);
        var __deptCarIds =cache.get("deptCarIds");
        if(__deptCarIds){
            res.json(__deptCarIds);
        }else{
            res.json(__deptCarIds);
        }
    }catch (e){
    }
});

router.post('/queryTreeData',function (req, res, next) {
    carTree = [
        // {
        //     text: "所有客户",
        //     state:{
        //         expanded:true
        //     },
        //     nodes:[]
        // }
    ];
    carTreeJson={};
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    qs.sid = sid;
    var _online = req.param("online");
    var _url = pro.devServeraddr + "heb/baseCar/loadZTree?sid="+sid;
    var _baseCarNo = req.param("baseCarNo");
    var _initCarId = req.param("pointCarId");
    if(_online === "0"){
        _url = _url +"&online=0"
    }else if(_online === "1"){
        _url = _url +"&online=1"
    }
    if(_baseCarNo){
        searchCarNo=true;
        _url = pro.devServeraddr + "heb/baseCar/loadZTree?sid="+sid;
        _url = _url +"&baseCarNo="+_baseCarNo
    }else{
        searchCarNo=false;
    }
    if(_initCarId){
        _initCheckCarId = _initCarId
    }else{
        _initCheckCarId = null;
    }
    qs.online = _online;
    qs.baseCarNo = _baseCarNo;
    qs.pointCarId = _initCarId;
    // console.log("--ur--"+_url);
    request({
        // url:"http://localhost:3001/testData/carTree.json",
        // url:encodeURI(_url),
        // method: "GET",
        // qs: {online:'0'}

        url:pro.localServeraddr+"monitor/queryTreeData",
        // url:encodeURI(_url),
        method: "POST",
        qs:qs
    },function (error, response, body) {
        // console.log(response);
        // console.log("车辆数据queryTreeData--"+body);
        // console.log(JSON.parse(body).length);
        try{
            // if(!error && response.statusCode == 200){
            //     getTrees(JSON.parse(body));
            // }else{
            // }
            var data = body;
            if(typeof body === "string"){
                data = JSON.parse(body);
            }
            var resultObj = {
                carTree:data.carTree,
                carTreeJson:data.carTreeJson
            };
            if(_online === "0"){
                cache.put("unOnlineCarTreeObj",resultObj);
            }else if(_online === "1"){
                cache.put("onLinecarTreeObj",resultObj);
            }
            cache.put("cacheCarTreeObj_"+pro.loginUserId,resultObj);
            res.json(resultObj);
        }catch (e){
            console.log("异常了...");
            console.log(e.message)
        }

    });
});

router.post('/refZTree',function (req, res, next) {
    carTree = [
        // {
        //     text: "所有客户",
        //     state:{
        //         expanded:true
        //     },
        //     nodes:[]
        // }
    ];
    carTreeJson={};
    var sid=auth.getSessionID(req, res, next);
    var __isSearch = false;
    var qs=req.body;
    qs.sid = sid;
    var _online = req.param("online");
    var _url = pro.devServeraddr + "heb/baseCar/refZTree?sid="+sid;
    var _baseCarNo = req.param("baseCarNo");
    var _initCarId = req.param("pointCarId");
    if(_online === "0"){
        __isSearch = true;
        _url = _url +"&online=0";
    }else if(_online === "1"){
        __isSearch = true;
        _url = _url +"&online=1"
    }
    if(_baseCarNo){
        __isSearch = true;
        searchCarNo=true;
        _url = pro.devServeraddr + "heb/baseCar/refZTree?sid="+sid;
        _url = _url +"&baseCarNo="+_baseCarNo
    }else{
        searchCarNo=false;
    }
    if(_initCarId){
        __isSearch=true;
        _initCheckCarId = _initCarId
    }else{
        _initCheckCarId = null;
    }

    qs.online = _online;
    qs.baseCarNo = _baseCarNo;
    qs.pointCarId = _initCarId;
    // console.log("--url:"+_url);
    request({
        url:pro.localServeraddr+"monitor/refZTree",
        // url:encodeURI(_url),
        method: "POST",
        qs:qs
    },function (error, response, body) {
        //console.log("车辆数据"+body);
        console.log("reftree数据已获取");
        // console.log(JSON.parse(body).length);
        try{
            // if(!error && response.statusCode == 200){
            //     getTrees(JSON.parse(body));
            // }else{
            // }
            var data = body;
            if(typeof body === "string"){
                data = JSON.parse(body);
            }
            var resultObj = {
                carTree:data.carTree,
                carTreeJson:data.carTreeJson
            };
            if(_online === "0"){
                cache.put("unOnlineCarTreeObj",resultObj);
            }else if(_online === "1"){
                cache.put("onLinecarTreeObj",resultObj);
            }
            if(!__isSearch){
                cache.put("cacheCarTreeObj_"+pro.loginUserId,resultObj);
                pro.gClient.set("carTreeObj_"+pro.loginUserId,"");
                pro.gClient.set("carTreeObj_"+pro.loginUserId,JSON.stringify(resultObj));
            }
            res.json(resultObj);
        }catch (e){
            console.log("异常了...");
            console.log(e.message)
        }

    });
});

router.post('/refDeptIdsRef',function (req, res, next) {
    var sid=auth.getSessionID(req, res, next);
    var _url = pro.devServeraddr + "heb/baseCarDept/queryDeptIdsRef";
    console.log("--url:"+_url);
    request({
        // url:"http://localhost:3001/testData/carTree.json",
        url:encodeURI(_url),
        method: "GET",
    },function (error, response, body) {
        try{
            if(!error && response.statusCode == 200){
                // console.log("---deptCarids---");
                // console.log(body);
                cache.put("deptCarIds",JSON.parse(body));
                res.json(JSON.parse(body));
            }

        }catch (e){
            console.log(e.message)
        }

    });
});

router.post('/querySessionAllData',function (req, res, next) {
    carTree = [
    ];
    carTreeJson={};
    var _initCarId = req.param("pointCarId");
    // console.log(req.session.treeData);
    //console.log(req.session.treeData.treeJson);
    if(_initCarId){
        _initCheckCarId = _initCarId
    }else{
        _initCheckCarId = null;
    }
    try {
        var sid=auth.getSessionID(req, res, next);
        // console.log("------加载车辆数据-------");
        //console.log(req.session.treeData.treeJson);

        console.log(pro.loginUserId);

        pro.gClient.get("carTreeObj_"+pro.loginUserId,function (error, resu) {
            if(error) {
                console.log(error);
            } else {
                console.log(resu);
                console.log(pro.loginUserId);
                res.json(JSON.parse(resu));
            }
        });

        //var __carTreeObj =cache.get("cacheCarTreeObj_"+pro.loginUserId);
        //  console.log("--");
        // console.log(__carTreeObj);
        //if(__carTreeObj){
        // req.session.treeData = req.session.treeData;
        // var _parseTreeJson = JSON.parse(req.session.treeData.treeJson);
        // console.log(new Date());
        // getTrees(_parseTreeJson);
        // var resultObj = __carTreeObj;
        // _carTreeObj = __carTreeObj;
        // //console.log(new Date());
        // res.json(resultObj);
        // }else{
        //     res.json(_carTreeObj);
        //     // res.redirect(307,"/monitor/queryTreeData");
        // }
    }catch (e){
        //res.redirect(307,"/monitor/queryTreeData");
    }

});

router.post('/querySessionOnlineData',function (req, res, next) {
    carTree = [
    ];
    carTreeJson={};
    var _initCarId = req.param("pointCarId");
    // console.log(req.session.treeData);
    //console.log(req.session.treeData.treeJson);
    if(_initCarId){
        _initCheckCarId = _initCarId
    }else{
        _initCheckCarId = null;
    }
    try {
        var sid=auth.getSessionID(req, res, next);
        var qs=req.body;
        qs.sid = sid;
        qs.pointCarId = _initCarId;
        // console.log("------加载车辆数据-------");
        //console.log(req.session.treeData.treeJson);
        var __carTreeObj =cache.get("onLinecarTreeObj");
        //  console.log("--");
        // console.log(__carTreeObj);
        if(__carTreeObj){
            // req.session.treeData = req.session.treeData;
            // var _parseTreeJson = JSON.parse(req.session.treeData.treeJson);
            // console.log(new Date());
            // getTrees(_parseTreeJson);
            var resultObj = __carTreeObj;
            _carTreeObj = __carTreeObj;
            //console.log(new Date());
            //cache.put("carTreeObj",__carTreeObj);
            res.json(resultObj);
        }else{
            // var _url = pro.devServeraddr + "heb/baseCar/refZTree?sid="+sid;
            // _url = _url +"&online=1";
            qs.online = "1";
            request({
                url:pro.localServeraddr+"monitor/querySessionOnlineData",
                //url:encodeURI(_url),
                method: "POST",
                qs:qs
            },function (error, response, body) {
                //console.log("querySessionOnlineData车辆数据:"+body);
                // console.log(JSON.parse(body).length);
                try{
                    // if(!error && response.statusCode == 200){
                    //     getTrees(JSON.parse(body));
                    // }else{
                    // }
                    var data = body;
                    if(typeof data === "string"){
                        data = JSON.parse(body);
                    }
                    var resultObj = data;
                    cache.put("onLinecarTreeObj",resultObj);
                    res.json(resultObj);
                }catch (e){
                    console.log("异常了...");
                    console.log(e.message)
                }

            });
        }
    }catch (e){
        //res.redirect(307,"/monitor/queryTreeData");
    }

});

router.post('/querySessionUnOnlineData',function (req, res, next) {
    carTree = [
    ];
    carTreeJson={};
    var _initCarId = req.param("pointCarId");
    // console.log(req.session.treeData);
    //console.log(req.session.treeData.treeJson);
    if(_initCarId){
        _initCheckCarId = _initCarId
    }else{
        _initCheckCarId = null;
    }
    try {
        var sid=auth.getSessionID(req, res, next);
        var qs=req.body;
        qs.sid = sid;
        qs.pointCarId = _initCarId;
        var __carTreeObj =cache.get("unOnlineCarTreeObj");
        if(__carTreeObj){
            var resultObj = __carTreeObj;
            _carTreeObj = __carTreeObj;
            res.json(resultObj);
        }else{
            // var _url = pro.devServeraddr + "heb/baseCar/refZTree?sid="+sid;
            // _url = _url +"&online=0";
            qs.online = "0";
            request({
                url:pro.localServeraddr+"monitor/querySessionUnOnlineData",
                // url:encodeURI(_url),
                method: "POST",
                qs:qs
            },function (error, response, body) {
                //console.log("querySessionUnOnlineData车辆数据:"+body);
                try{
                    // if(!error && response.statusCode == 200){
                    //     getTrees(JSON.parse(body));
                    // }else{
                    // }
                    var data = body;
                    if(typeof data === "string"){
                        data = JSON.parse(body);
                    }
                    var resultObj = data;
                    cache.put("unOnlineCarTreeObj",resultObj);
                    res.json(resultObj);
                }catch (e){
                    console.log("异常了...");
                    console.log(e.message)
                }
            });
        }
    }catch (e){
        //res.redirect(307,"/monitor/queryTreeData");
    }

});
router.post('/queryTreeNodeInfo',function (req,res,next) {
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByTrackCar",
        method: "POST",
        qs:req.body
    },function (error, response, body) {
        var resultJSON = {
            message:"",
            isSuccess:true,
            data:null
        };
        if(!error && response.statusCode == 200){
            // console.log("ndoeinfo---"+body);
            try {
                var result = JSON.parse(body);
                if(result.success == true){
                    resultJSON.isSuccess=true;
                    resultJSON.data=result.data;
                    resultJSON.message="查询数据成功！"
                }else{
                    resultJSON.isSuccess=false;
                    resultJSON.data = null;
                    resultJSON.message="查询数据异常，请稍后重试！"
                }
            }catch (e){
                console.log(e.message)
                resultJSON.isSuccess=false;
                resultJSON.data = null;
                resultJSON.message="查询数据异常，请稍后重试！"
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.data = null;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(resultJSON);
    });



    // res.json(treeNodes)
});
router.post('/queryHistotryInfo',function (req,res,next) {
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    qs.sid = sid;
    request({
        url:pro.devServeraddr + "heb/hisGpsInfo/queryTableGpsData",
        method: "POST",
        qs:qs
    },function (error, response, body) {
        var resultJSON = {
            message:"",
            isSuccess:true,
            data:null
        };
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                // console.log("ndoeinfo---"+body);
                if(result.success == true){
                    resultJSON.isSuccess=true;
                    resultJSON.data=result.rows;
                }else{
                    resultJSON.isSuccess=false;
                    resultJSON.message="查询数据异常，请稍后重试！"
                }
            }catch (e){
                console.log(e.message);
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(resultJSON);
    });



    // res.json(treeNodes)
});
router.get('/queryCarStatus',function (req,res,next) {
    var carsJSON = [];
    var status = req.param("tabCode");
    for(var i=0;i<cars.length;i++){
        var car = cars[i];
        if(car["status"] == status){
            carsJSON.push(car);
        }
    }
    res.json(carsJSON)
});


router.post('/listSessionCountCar',function (req,res,next) {
    //var sid=auth.getSessionID(req, res, next);
    // var qs=req.body;
    // qs.sid = sid;
    try{
        // var result = JSON.parse(body);
        //console.log(pro.carTrees);
        var __carTrees = cache.get("carTrees");
        if(__carTrees){
            resultJSON.isSuccess=true;
            // if(__carTrees.carTreeCount){
            //     _carCountObj = pro.carTrees;
            // }else{
            //     pro.carTrees=_carCountObj;
            // }
            //console.log(_carCountObj);
            resultJSON.data=__carTrees.carTreeCount;
            resultJSON.onlineStr =__carTrees.onLineCar;
            resultJSON.offlineStr =__carTrees.offLineCar;
            cache.put("carTrees",__carTrees);
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
    }catch (e){
        console.log(e.message);
        resultJSON.isSuccess=false;
        resultJSON.message="查询数据异常，请稍后重试！"
    }
    res.json(resultJSON);
});
router.get('/listByCountCar',function (req,res,next) {
    var sid=auth.getSessionID(req, res, next);
    // var qs=req.body;
    // qs.sid = sid;
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByCountCar?sid="+sid,
        method: "GET",
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.success){
                    var __carTreeCount = {};
                    resultJSON.isSuccess=true;
                    resultJSON.data=result.data;
                    resultJSON.onlineStr =result.onlineStr;
                    resultJSON.offlineStr =result.offlineStr;

                    __carTreeCount.carTreeCount=result.data;
                    __carTreeCount.onLineCar =result.onlineStr;
                    __carTreeCount.offLineCar =result.offlineStr;

                    cache.put("carTrees",__carTreeCount);
                }else{
                    resultJSON.isSuccess=false;
                    resultJSON.message="查询数据异常，请稍后重试！"
                }
            }catch (e){
                console.log(e.message);
                resultJSON.isSuccess=false;
                resultJSON.message="查询数据异常，请稍后重试！"
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(resultJSON);
    });
});
router.get('/listByMainCarCount',function (req,res,next) {
    var jsonResult = {
        total:0,
        wxnum:0,
        isSuccess:false,
        yxnum:0
    };
    var allCarIds = req.param("allCarIds");
    var qs=req.query;
    var sid=auth.getSessionID(req, res, next);
    qs.sid = sid;
    // console.log("关注车辆参数:"+allCarIds);
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByMainCarCount",
        method: "POST",
        qs:qs
    },function (error, response, body) {
        var jsonResult = {
            total:0,
            wxnum:0,
            isSuccess:false,
            yxnum:0
        };
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.success == true){
                    jsonResult.total = result.data.totalNum;
                    jsonResult.wxnum = result.data.wxnum;
                    jsonResult.yxnum = result.data.yxnum;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "离线表格查询数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "离线表格查询数据异常，请稍后重试！";
                // console.log(e.message);
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
router.get('/his', function(req, res, next) {
    auth.checkAuth(req, res, next);
    var pathname = url.parse(req.url).pathname;  //pathname => list
    var arg = url.parse(req.url, true).query;   //arg1 => {name:'a',id:'5'}
    var query=req.query;//参数
    var carId=query.carId;
    var carNo=query.carNo;
    if(!carId){
        carId="0"
    }
    if(!carNo){
        carNo=""
    }
    res.render('map/oldMonitor',{jw:pro.jw,flag: false,serverurl:pro.serveraddr,carId:carId,carNo:carNo});

});
/**
 * 查询在线车辆接口
 */
router.post('/listByRealOnLineCar',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[]
    };
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    qs.sid = sid;
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByRealOnLineCar",
        method: "POST",
        qs:qs
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);

                if(result.success == true){
                    // console.log("rows:"+result.rows.length);
                    jsonResult.total = result.rows.length;
                    jsonResult.rows = result.rows;
                }else{
                    jsonResult.isSuccess=false;
                    jsonResult.message="查询数据异常，请稍后重试！"
                }
            }catch (e){
                jsonResult.isSuccess=false;
                jsonResult.message="查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess=false;
            jsonResult.message="查询数据异常，请稍后重试！"
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});

/**
 * 查询在线车辆树接口
 */
router.post('/listByRealOnLineCarTree',function (req,res,next) {
    carTree = [
        // {
        //     text: "所有客户",
        //     state:{
        //         expanded:true
        //     },
        //     nodes:[]
        // }
    ];
    var jsonResult = {
        total:0,
        rows:[]
    };
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    qs.sid = sid;
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByRealOnLineCar",
        method: "POST",
        qs:qs
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);

                if(result.success == true){
                    // console.log("rows:"+result.rows.length);
                    jsonResult.total = result.rows.length;
                    jsonResult.rows = result.rows;
                    getTrees(result.rows);
                }else{
                    jsonResult.isSuccess=false;
                    jsonResult.message="查询数据异常，请稍后重试！"
                }
            }catch (e){
                jsonResult.isSuccess=false;
                jsonResult.message="查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess=false;
            jsonResult.message="查询数据异常，请稍后重试！"
        }
        res.json(carTree);
    });

    // res.json(treeNodes)
});
/**
 * 查询离线车辆接口
 */
router.post('/listByRealOutLineCar',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };
    var sblxday = req.param("sblxday");
    var deptname =req.param("deptName");
    // console.log("sblxday>>"+sblxday);
    // console.log("deptname>>"+deptname);
    var _url = pro.devServeraddr + "heb/realGpsInfo/listByRealOutLineCar";
    // if(sblxday){
    //     _url = _url+"?sblxday="+sblxday
    // }
    // if(deptname){
    //     if(_url.indexOf("?")>-1){
    //         _url = _url+"&deptName="+deptname
    //     }else{
    //         _url = _url+"?deptName="+deptname
    //     }
    // }
    //console.log("离线_url>>"+_url);
    var sid=auth.getSessionID(req, res, next);
    request({
        url:_url,
        method: "POST",
        qs:{
            sblxday:sblxday,
            deptName:deptname,
            sid:sid
        }
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.success == true){
                    jsonResult.total = result.rows.length;
                    jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "离线表格查询数据异常，请稍后重试！";
                }
            }catch(e){
                console.log("程序异常>>"+e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
/**
 * 查询未按时上线车辆接口
 */
router.post('/listByWSXCar',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };
    var sid=auth.getSessionID(req, res, next);
    var qs = req.body;
    var sblxwxday = req.param("sblxwxday");
    qs.sid=sid;
    qs.sblxwxday = sblxwxday;
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByWSXCar",
        method: "POST",
        qs:qs,
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.success == true){
                    jsonResult.total = result.rows.length;
                    jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "离线表格查询数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "离线表格查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
/**
 * 查询未行使车辆接口
 */
router.post('/listByWXSCar',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };
    var sid=auth.getSessionID(req, res, next);
    //var qs = req.body;
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByWXSCar?wxsday="+req.param("wxsday")+"&sid="+sid,
        method: "POST",
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.success == true){
                    jsonResult.total = result.rows.length;
                    jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "离线表格查询数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "离线表格查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});

/**
 * 查询关注车辆接口
 */
router.post('/listByCarIds',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };
    var sid=auth.getSessionID(req, res, next);
    var allCarIds = req.param("allCarIds");
    var qs=req.body;
    qs.sid = sid;
    // console.log("关注车辆参数:"+allCarIds);
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByCarIds",
        method: "POST",
        qs:qs
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);

                if(result.success == true){
                    jsonResult.total = result.rows.length;
                    jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "关注车辆查询数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "关注车辆查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "关注车辆查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});

/**
 * 查询报警信息
 */
router.post('/listByCarWaring',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByCarWaring",
        method: "POST"
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);

                if(result.success == true){
                    jsonResult.total = result.rows.length;
                    jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "报警信息查询数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "报警信息查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "报警信息查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
/**
 * 处理报警信息
 */
router.post('/updateWarningType',function (req,res,next) {
    var id = req.param("id");
    var type =1;
    request({
        url:pro.devServeraddr + "heb/tabWaringInfo/updateType",
        method: "POST",
        qs:{
            "id":id,
            "type":type
        }
    },function (error, response, body) {
        // console.log("处理报警信息--"+body);
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                resultJSON.data = result
            }catch (e){
                resultJSON.isSuccess = false;
                resultJSON.message = "离线表格查询数据异常，请稍后重试！";
                console.log(e.message)
            }

        }else{
            resultJSON.isSuccess = false;
            resultJSON.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(resultJSON);
    });

    // res.json(treeNodes)
});
router.post('/queryDuanDianReport',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    if(!qs.waringstate){
        qs.waringstate = 0;
    }
    qs.sid = sid;
    request({
        url:pro.devServeraddr + "heb/tabWaringInfo/list",
        method: "POST",
        qs:qs,
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);

                if(result.success == true){
                    jsonResult.total = result.total;
                    jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                    jsonResult.carTotal = result.carTotal
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "断电报警查询数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "断电报警查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "断电报警查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

});
var url = require('url');
router.get('/editInfo', function(req, res){
    var pathname = url.parse(req.url).pathname;  //pathname => list
    var arg = url.parse(req.url, true).query;   //arg1 => {name:'a',id:'5'}
    var query=req.query;//参数
    request({
        url: pro.serveraddr+'/baseCar/editInfo',
        method: "POST",
        qs: arg
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            try{
                var data=JSON.parse(body);
                if(data.success == true){
                    // console.log("车辆信息结果>>"+data.success);
                    res.json(data);
                }else {
                    // console.log("error= " + data.msg );
                    res.json(data.msg);
                }
            }catch (e){
                console.log(e.message);
            }
        }
    });
});
/**
 * 查询拆机信息
 */
router.post('/chaijiList',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    qs.sid = sid;
    request({
        url:pro.devServeraddr + "heb/baseTerminal/listStatus",
        method: "POST",
        qs:qs
    },function (error, response, body) {
        // console.log("拆机记录信息--"+body);
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);

                if(result.success == true){
                    jsonResult.total = result.rows.length;
                    jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "拆机记录表格查询数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "拆机记录查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "拆机记录查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
/**
 * 保存重点监控数据id
 */
router.post('/makeZDJKCarIds',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };

    var sid=auth.getSessionID(req, res, next);
    var carIds = req.body["carIds"];
    console.log("sid>>"+sid);
    console.log("carIds>>"+carIds);
    req.body["sid"] = sid;
    request({
        url:pro.devServeraddr + "heb/baseCar/makeZDJKCarIds",
        method: "POST",
        qs:req.body
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);

                if(result.success == true){
                    //jsonResult.total = result.rows.length;
                    //jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "保存重点监控数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "保存重点监控数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "保存重点监控数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
/**
 * 查询重点监控数据id
 */
router.post('/queryZDJKCarIds',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:"",
        data:null
    };
    var sid=auth.getSessionID(req, res, next);
    console.log("sid>>"+sid);
    // var carIds = req.param("carIds");
    request({
        url:pro.devServeraddr + "heb/baseCar/queryZDJKCarIds",
        method: "POST",
        qs:{
            "sid":sid
        }
    },function (error, response, body) {
        // console.log(body);
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.success == true){
                    //jsonResult.total = result.rows.length;
                    //jsonResult.rows = result.rows;
                    jsonResult.data = result.obj;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "获取关注数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "获取关注数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "获取关注数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
/**
 * 实时监控关注车辆
 */
router.post('/makeGzCarIds',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:""
    };

    var sid=auth.getSessionID(req, res, next);
    console.log("sid>>"+sid);
    var carIds = req.body["carIds"];
    request({
        url:pro.devServeraddr + "heb/baseCar/makeGzCarIds",
        method: "POST",
        qs:{
            "carIds":carIds,
            "sid":sid
        }
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);

                if(result.success == true){
                    //jsonResult.total = result.rows.length;
                    //jsonResult.rows = result.rows;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "保存重点监控数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "保存重点监控数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "保存重点监控数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
/**
 * 查询实时监控关注车辆
 */
router.post('/queryGzCarIds',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:"",
        data:null
    };
    var sid=auth.getSessionID(req, res, next);
    console.log("sid>>"+sid);
    // var carIds = req.param("carIds");
    request({
        url:pro.devServeraddr + "heb/baseCar/queryGzCarIds",
        method: "POST",
        qs:{
            "sid":sid
        }
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.success == true){
                    //jsonResult.total = result.rows.length;
                    //jsonResult.rows = result.rows;
                    jsonResult.data = result.obj;
                    jsonResult.isSuccess = true;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "获取关注数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "获取关注数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "获取关注数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
router.get('/warningCarTotal',function (req,res,next) {
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    qs.sid = sid;
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/carTotal",
        method: "GET",
        qs:qs
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.success){
                    resultJSON.isSuccess=true;
                    resultJSON.data=result.data;
                }else{
                    resultJSON.isSuccess=false;
                    resultJSON.message="查询数据异常，请稍后重试！"
                }
            }catch (e){
                resultJSON.isSuccess=false;
                resultJSON.message="查询数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(resultJSON);
    });
});
router.post('/validateService',function (req,res,next) {
    var jsonResult = {
        total:0,
        rows:[],
        isSuccess:false,
        message:"",
        data:null
    };
    var sid=auth.getSessionID(req, res, next);
    var qs = req.body;
    qs.sid = sid;
    console.log("sid>>"+sid);
    request({
        url:pro.devServeraddr + "heb/baseTerminal/validateService",
        method: "POST",
        qs:qs
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            try{
                var result = JSON.parse(body);
                if(result.isSuccess == true){
                    jsonResult = result;
                }else{
                    jsonResult.isSuccess = false;
                    jsonResult.message = result.msg ? result.msg : "获取关注数据异常，请稍后重试！";
                }
            }catch (e){
                jsonResult.isSuccess = false;
                jsonResult.message = "获取关注数据异常，请稍后重试！";
                console.log(e.message)
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "获取关注数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });
});
module.exports =router;